# -*- coding: utf-8 -*-
"""
Created on Fri Sep 24 16:45:19 2021

@author: chibi
"""
from PIL import Image, ImageDraw , ImageFont
import cv2
import numpy
import  requests
import os
import json
import socket
import time 
import datetime
home = os.getcwd() #获取当前文件运行的根目录
img_name= 'images' #图片存放位置
img_dir = '%s/%s/' %(home,img_name)
url = 'https://www.weatherol.cn/api/home/getCurrAnd15dAnd24h?cityid=101020100'

esp_ip  = '192.168.88.100'
esp_port = 8888

serverAddressPort   = (esp_ip, esp_port)
bufferSize          = 1024
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

def get_data(url):
    
    get_html = requests.get(url)
   
    get_html.encoding='utf-8'
    h = get_html.text
    data = json.loads(h)
    #print(data)
    #print(type(data))
    text= data
    raw = {}
    raw['airpressure'] = text['data']['current']['current']['airpressure']
    raw['visibility'] = text['data']['current']['current']['visibility']
    raw['windpower'] = text['data']['current']['current']['windpower']
    raw['feelstemperature'] = text['data']['current']['current']['feelstemperature']
    raw['weather'] = text['data']['current']['current']['weather']
    raw['winddir'] = text['data']['current']['current']['winddir']
    raw['humidity'] = text['data']['current']['current']['humidity']
    raw['temperature'] = text['data']['current']['current']['temperature']
    
    raw['weatherPic'] = text['data']['current']['current']['weatherPic']
    raw['nongLi'] = text['data']['current']['nongLi']
    raw['tips'] = text['data']['current']['tips']
    
    raw['Pic_url'] = 'https://www.weatherol.cn/hao123/images/icon/%s.png' %  raw['weatherPic']
    return raw


def wirite_img(img_icon,pic_url):
    global temp_img
    temp_img ='%s%s.png'  %( img_dir,img_icon)
    #print(temp_img )
    if not os.path.isdir(img_dir) : #没有文件夹才创建
        os.mkdir(img_dir)
    
    if not os.path.isfile(temp_img): #没有找到图片文件
         download_img(pic_url)
    else:
        print('图片已存在无需下载')
    

def download_img(url):
    global temp_img
    get_img = requests.get(url)
    print(get_img.headers) 
    if get_img.headers['Content-Type']== 'image/png':
        print('文件开始写入')
        with open(temp_img,'wb') as image_:
            image_.write(get_img.content)
            



#新建图片
def bg_new():
    
    bg_ = Image.new('RGB',(128,64))
    return bg_

#opencv 转 pillow
def cvtopil(img):
    temp_img = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
    return temp_img
#pillow 转 opencv
def piltocv(img):
    temp_img = cv2.cvtColor(numpy.asarray(img),cv2.COLOR_RGB2BGR)
    return temp_img

font_file = r'simhei.ttf'
def chinese_text(img,temp_t,place,fong_size):
    font = ImageFont.truetype(font_file ,int(fong_size))# 前面是字体路径 后面是字体大小

    draw = ImageDraw.Draw(img) 

    draw.text(place ,temp_t, font = font ,fill='white')
    
    #bg_img.show()
    
    return img

def getdata():
    global data
    bg_ = bg_new()
    data = get_data(url)
    wirite_img(data['weatherPic'],data['Pic_url'])
    
    #print(data)
    w_pic = '%s%s.png' % (img_dir,data['weatherPic'])
    #print(w_pic)
    
    #去掉透明图层 转成灰阶
    img = cv2.imread(w_pic, cv2.IMREAD_UNCHANGED)
    img_gray = 255-(255 - img[:, :, 3])
    
    new_img =  cvtopil(img_gray)
    #new_img.show()


    
    #重新修改图片大小
    new_img.thumbnail((30,30), Image.ANTIALIAS)
    
    chinese_text(bg_,'气压:%s' % data['airpressure'],(40,0),15)
    chinese_text(bg_,'%s:%s' % (data['winddir'],data['windpower']),(40,15),15)
    chinese_text(bg_,'%s' % data['weather'],(0,30),15)
    chinese_text(bg_,'温度:%s' % data['temperature'],(40,30),15)
    chinese_text(bg_,'湿度:%s' % data['humidity'],(80,48),12)
    chinese_text(bg_,'体感:%s' % data['feelstemperature'],(0,48),12)
    
    #new_ = renewsize.crop()
    #print(renewsize)
    #拼合图片在新图层
    bg_.paste(new_img, (0,0))
    #bg_.show()
    #将数据发送到oled屏幕
    readimg(bg_)
    
    print('数据已发送')
    time.sleep(5)



def readimg(im):
    dim = (128, 64)
  
    # resize image
    im.thumbnail(dim, Image.ANTIALIAS)
    #im.show()
    im = im.convert("L")
    #im = im.convert("1")
    text =''
    point = 0
    for y in range (64):
        for x in range (128):
            if im.getpixel((x,y)) <50:
                get_point = 0
            else:
                get_point = 1
                
            
            now = int( get_point )<<(3-x%4) 
            #位数1/0 转二进制
           
            point += now
            
            if (x%4 ==3):
                text += hex(point)[2:]
               
                #text += "|"
                point = 0 #还原
    text += "#"
    #print(text)
    
    UDPClientSocket.sendto(text.encode('utf-8'), serverAddressPort)
  
def showtimes():
    bg_ = bg_new()
    now = datetime.datetime.now().strftime('%H:%M:%S')
    chinese_text(bg_,'时间:',(0,0),20)
    chinese_text(bg_,now,(0,15),16)
     
    readimg(bg_)
    
    #print('数据已发送')
     
getdata()

def main():
    while True:
        nowtime =int ( time.time() * 1000)
        #print (nowtime)
        if str(nowtime)[-4:] == '1000':
            print (nowtime)
            getdata()
        elif  str(nowtime)[-3:] == '100' or  str(nowtime)[-3:] == '200' or\
            str(nowtime)[-3:] == '300' or  str(nowtime)[-3:] == '400' or\
            str(nowtime)[-3:] == '500' or  str(nowtime)[-3:] == '600' or\
            str(nowtime)[-3:] == '700' or  str(nowtime)[-3:] == '800' or\
            str(nowtime)[-3:] == '900' or  str(nowtime)[-3:] == '000' :
            showtimes()
    
main()